// 导出页面为PDF
import { ref, Ref } from 'vue'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import { ElNotification } from 'element-plus'

// 定义参数的接口
interface ExportPDFParams {
  target: HTMLElement // 注意：确认 target 对象类型的准确性
  downloadName?: string
  scale?: number
  isDownload?: boolean
  isNotify?: boolean
}

// 使用泛型来定义返回值的类型
export function useExportPDF() {
  const downLoading: Ref<boolean> = ref(false)

  const exportPDF = (param: ExportPDFParams): Promise<string | void> => {
    // 提取参数，同时设置默认值
    const {
      target,
      downloadName = 'download',
      scale = 2,
      isDownload = true,
      isNotify = false,
    } = param

    if (isNotify) {
      ElNotification({
        title: '温馨提示',
        message: '如果数据庞大会导致下载缓慢哦，请您耐心等待！',
        type: 'info',
        duration: 3000,
      })
    }

    downLoading.value = true

    return new Promise<string | void>((resolve, reject) => {
      html2canvas(target, {
        allowTaint: true,
        backgroundColor: '#ffffff',
        scale,
      })
        .then((canvas) => {
          const contentWidth = canvas.width
          const contentHeight = canvas.height
          const pageHeight = (contentWidth / 592.28) * 841.89
          let leftHeight = contentHeight
          let position = 0
          const imgWidth = 595.28
          const imgHeight = (592.28 / contentWidth) * contentHeight
          const pageData = canvas.toDataURL('image/jpeg', 1.0)
          const pdf = new jsPDF('p', 'pt', 'a4')

          if (leftHeight < pageHeight) {
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          } else {
            while (leftHeight > 0) {
              pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
              leftHeight -= pageHeight
              position -= 841.89
              if (leftHeight > 0) {
                pdf.addPage()
              }
            }
          }

          if (isDownload) {
            pdf.save(`${downloadName}.pdf`)
          }
          resolve()
        })
        .catch((err) => {
          reject(err)
        })
        .finally(() => {
          downLoading.value = false
        })
    })
  }

  return {
    exportPDF,
    downLoading,
  }
}
